#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author： 青城子
# datetime： 2022/3/1 20:42 
# ide： PyCharm


"""
创建截图目录
"""

import os
import time

from conf import settings
from utils.loghandler import logger


class CreateDir:
    def __init__(self):
        self.img_time = time.strftime("%Y-%m-%d %H_%M_%S")  # 生成截图片已当前时间命名图片名称
        self.dir_time = time.strftime("%Y-%m-%d")  # 当日截图目录名称
        self.dir_root = settings.BASE_DIR  # 项目根目录
        self.screen_dir = settings.DIR_PATH_DICT.get("screenshots")

    def create_screens_hot_dir(self, *args):
        """
        创建截图目录
        :return:
        """
        # 创建截图一级目录
        try:
            if os.path.exists(self.screen_dir):
                pass
            else:
                os.mkdir("{0}".format(self.screen_dir))
        except Exception as error:
            logger().info("创建截图目录失败:{0}".format(error))

        # 创建二级目录
        try:
            if os.path.exists(r"{0}\{1}".format(self.screen_dir, self.dir_time)):
                """
                 判断screenshots目录下是否存在(2020-04-15)格式命名的目录
                """
                pass
            else:
                os.mkdir(r"{0}\{1}".format(self.screen_dir, self.dir_time))
        except Exception as error:
            logger().info("创建每日截图目录失败:{0}".format(error))

        # 创建三级目录用于存放用例执行成功时截图
        try:
            if os.path.exists(r"{0}\{1}\{2}".format(self.screen_dir, self.dir_time, "success")):
                pass
            else:
                os.mkdir(r"{0}\{1}\{2}".format(self.screen_dir, self.dir_time, "success"))
        except Exception as error:
            logger().info("创建每日成功截图目录失败:{0}".format(error))
        direct_success = r"{0}\{1}\{2}".format(self.screen_dir, self.dir_time, "success")

        # 创建三级目录，用于保存用例执行失败时截图信息
        if args[0]:
            try:
                if os.path.exists(r"{0}\{1}\{2}".format(self.screen_dir, self.dir_time, "errordir")):
                    pass
                else:
                    os.mkdir(r"{0}\{1}\{2}".format(self.screen_dir, self.dir_time, "errordir"))

            except Exception as error:
                logger().info("每日错误目录失败:{0}".format(error))

        direct_error = r"{0}\{1}\{2}".format(self.screen_dir, self.dir_time, "errordir")
        return direct_success, direct_error,

    def screenshots(self, type_str=None, error=None):
        """
        截图
        :return:
        """
        dir_success, dir_error = self.create_screens_hot_dir(error)
        # 用例执行成功时页面截图
        if type_str:
            image_page = r"{0}\{1}{2}.png".format(dir_success, type_str, self.img_time)
        else:
            image_page = r"{0}\{1}.png".format(dir_success, self.img_time)

        if error:
            # 代码执行错误时，进行截图
            image_page_error = r"{0}\{1}.png".format(dir_error, self.img_time)
            print(image_page_error)
        else:
            print(image_page)


if __name__ == '__main__':
    obj_cr = CreateDir()
    obj_cr.screenshots()